﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SoftwareConsulting.BI11.NumericalMethods.LinearEquationsSystems
{
    /// <summary>
    /// Класс метода секущей для решения СЛАУ
    /// </summary>
    public class SecantMethod
    {
        private const double _startPrecision = 0.0001f;
        private double _result;
        private bool _hasSolution;

        /// <summary>
        /// Конструктор класса
        /// </summary>
        /// <param name="stepsNumber">число шагов метода</param>
        /// <param name="point1"></param>
        /// <param name="point2"></param>
        /// <param name="function"></param>
        public SecantMethod(int stepsNumber, double point1, double point2, FunctionWithOneArgument function)
        {
            _result = 0;
            _hasSolution = false;
            double p2 = _startPrecision;
            double p1 = _startPrecision;
            double p0 = _startPrecision;
            double prec = _startPrecision;
            int i = 0;
            p0 = function(point1);
            p1 = function(point2);
            p2 = p1 - function(p1) * (p1 - p0) / (function(p1) - function(p0)); //формула секущей
            for (i = 0; i < stepsNumber; i++)
            {
                p0 = p1;
                p1 = p2;
                p2 = p1 - function(p1) * (p1 - p0) / (function(p1) - function(p0));
                if (Math.Abs(p2) <= prec)
                {
                    _hasSolution = true;
                    _result = p2;
                    return;
                }
            }            
        }

        /// <summary>
        /// Возвращает решение
        /// </summary>
        /// <returns></returns>
        public double GetSolution()
        {
            return _result;
        }

        /// <summary>
        /// Возвращает флаг, имеет ли СЛАУ решения
        /// </summary>
        public bool HasSolution
        {
            get
            {
                return _hasSolution;
            }
        }
    }
}
